﻿// Sheego.Service.X400
// Copyright(C) 2015 Schwab Versand GmbH
//
// This source file is subject to the Microsoft Public License(Ms-PL).
// http://www.opensource.org/licenses/ms-pl.html
// All other rights reserved.
using Sheego.Service.X400.Job.Shared;
using Sheego.Service.X400.Job.Shared.Locator;
using Sheego.Service.X400.Job.Shared.Parser;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace Sheego.Service.X400.Job.Impl.Parser
{
    class UAFIResponseParser : IUAFIResponseParser
    {
        #region IUAFIResponseParser Members


        static Regex regexLogon = new Regex(@"^Logon.*\(OK\)");
        static Regex regexFetching = new Regex(@"^Fetching");
        static Regex regexDelivered = new Regex(@"^Delivered");
        static Regex regexFetched = new Regex(@"^Fetched.*\(OK\).*""([a-zA-Z0-9]+)\.hdr");
        static Regex regexFetchedNone = new Regex(@"Fetched : NONE");
        public IUAFIResponse Parse(IList<string> Lines)
        {

            if (Lines == null)
                throw new ArgumentNullException("Lines");
            if (Lines.Count == 0)
                throw new ArgumentNullException("Lines");

            var response = JobLocator.GetResponse();
            response.Success = false;
            response.StatusText = "unknown";
            response.Messages = new List<String>();

            foreach (var Line in Lines)
            {
                if (regexLogon.Match(Line).Success)
                {
                    response.Success = true;
                    continue;
                }
                if (regexFetchedNone.Match(Line).Success)
                    continue;
                if (regexFetching.Match(Line).Success)
                    continue;
                if (regexDelivered.Match(Line).Success)
                    continue;


                Match match = regexFetched.Match(Line);
                if (match.Success)
                {
                    response.Messages.Add(match.Groups[1].Value);
                    continue;
                }


                //Fehler
                response.StatusText = Line;
                response.Success = false;
                break;
            }

            return response;

        }



        public IUAFIResponse ParseException(Exception ex)
        {
            if (ex == null)
                throw new ArgumentNullException("ex");

            var response = JobLocator.GetResponse();
            response.Success = false;
            response.StatusText = ex.Message;
            response.Messages = new List<String>();
            return response;

        }

        #endregion
    }
}
